<?php

namespace api\behaviors\actions;

use Yii;
use yii\base\Model;
use yii\helpers\Url;
use yii\web\ServerErrorHttpException;

/**
 * 创建一条记录。跟父类不同的是，本类在load用户填入的数据之前，首先执行loadDefaultValues()函数，将一些默认值填进去。
 * @package api\common\actions
 */
class CreateAction extends \yii\rest\CreateAction
{

    public function run()
    {
        //检查当前用户是否可以调用此接口
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }

        /* @var $model \yii\db\ActiveRecord */
        $model = new $this->modelClass([
            'scenario' => $this->scenario,
        ]);

        //首先载入默认值
        $model->loadDefaultValues();

        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        if ($model->save()) {
            $response = Yii::$app->getResponse();
            $response->setStatusCode(201); // 资源创建成功
            $id = implode(',', array_values($model->getPrimaryKey(true)));
            $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
        } elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
        }

        return $model;
    }
}
